package pl.ydp.components.mathcell.mathcell.preprocessing.multicharacter
{
	import flash.geom.Point;
	
	import pl.ydp.components.mathcell.mathrecognizer.structures.Range;

	public class StrokeBounds
	{
		public function StrokeBounds(strokePoints:Array, layout:Number){
			bounds = new Array;
			var coord:Number;
			var value:Number;
			
			for (var p:Number = 0 ; p < strokePoints.length ; p ++){
				if (layout == MultiCharactersLayout.HORIZONTAL){
					value = strokePoints[p].x;
					coord = Math.round(strokePoints[p].y);
				} else {
					value = strokePoints[p].y;
					coord = Math.round(strokePoints[p].x);					
				}
				
				setBoundsValue(coord, value);
			}
		}
		
		//-------------------------------------------------------------------
				
		private static const SMOOTH_COEFF:Number = 4;
		private var bounds:Array;
		
		//-------------------------------------------------------------------
		
		public function getBounds():Array{
			return bounds;
		}
		
		public function findDistance(test:StrokeBounds):Number{
			
			var forFrom:Number = 0;
			var forTo:Number = (bounds.length > test.getBounds().length) ? bounds.length : test.getBounds().length;
			
			var minDistance:Number = Infinity;
			
			for (var b:Number = forFrom ; b < forTo ; b ++){
				
				if (!bounds.hasOwnProperty(b.toString())  ||  !test.getBounds().hasOwnProperty(b.toString()))
					continue;
					
				var thisCurrBound:Range = bounds[b];
				var testCurrBound:Range = test.getBounds()[b];
				
				if (thisCurrBound.max < testCurrBound.min){
					if (testCurrBound.min - thisCurrBound.max < minDistance){
						minDistance = testCurrBound.min - thisCurrBound.max;
					}
				} else if (testCurrBound.max < thisCurrBound.min){
					if (thisCurrBound.min - testCurrBound.max < minDistance){
						minDistance = thisCurrBound.min - testCurrBound.max;
					}
				} else {
					minDistance = 0;
					break;
				}
			} 
			
			return minDistance;			
		}
		
		//-------------------------------------------------------------------
		
		private function setBoundsValue(coord:Number, value:Number):void{
			
			for (var currCoord:Number = coord-SMOOTH_COEFF ; currCoord < coord+SMOOTH_COEFF ; currCoord ++){				
			
				if (currCoord < 0)
					continue;
				
				if (bounds.hasOwnProperty((currCoord).toString())){
					if (value < bounds[currCoord].min){
						bounds[currCoord].min = value;
					} else if (value > bounds[currCoord].max){
						bounds[currCoord].max = value;
					}
				} else {
					bounds[currCoord] = new Range(value, value);
				}			
			}
		}
	}
}